/**
 * 无尽模式
 */
class EndLessUI extends UIBase{
    private game_group:eui.Group;
    private lb_prepare:eui.Label;
    private knife:knife;
    private touchId;
    private mIsDown: boolean;
    private isGameOver: boolean;
    private touchX;
    private touchY;
    private fruitList:fruit[] = [];
    private mMS: number = 300;
    private mStartTime:number;
    private system:particle.ParticleSystem;
    private count = 0;
    private lb_score:eui.Label;
    private btn_home:BaseButton;
    private lb_count:eui.Label;
    private floatWord_group:eui.Group;
    private img_miss:eui.Image;
    private bombList:Boom[] = [];

    public curSelectId:number;
    private curHitTotalNum:number = 0;//击中的总数
    private curCombNum:number = 0; //当前连击数
    private combHeightNum:number = 0;//最高连击数
    private isMiss:boolean;
    private img_prepare:eui.Image;

    private img_bg:eui.Image;
    private img_curKnife:eui.Image;
    public selectWeaponItem:EndLessSelectWeaponUI;

    private worldPoint:egret.Point;
    constructor()
    {
        super('EndLessView');
        this.touchChildren = false;
        this.curSelectId = 18;
        SoundManager.instance().playEndLessSound();
    }

    public init()
    {
        super.init(true);
        this.isMiss = false;
        this.lb_score.text = '0';
        this.curHitTotalNum = 0;//击中的总数
        this.curCombNum = 0; //当前连击数
        this.combHeightNum = 0;//最高连击数
        this.knife.anchorOffsetX = this.knife.width >> 1;
        this.knife.anchorOffsetY = this.knife.height >> 1;
        this.worldPoint = new egret.Point();
        this.mStartTime = egret.getTimer();
        egret.setTimeout(()=>{
            SoundManager.instance().playSound('ready_go');
            egret.Tween.get(this.img_prepare).to({
                scaleX:1,
                scaleY:1,
                alpha:1
            }, 600, egret.Ease.backIn).wait(400).set({
                source:'img_go_png'
            }).to({
                alpha:0,
                scaleX:0,
                scaleY:0
            }, 700, egret.Ease.backIn).call(this.gameStart, this);
        }, this, 300)
       
        this.addParticle();
    }

    public setWeaponId(e:BaseEvent)
    {
        let parma = e.param;
        let weaponId = parma['weaponId'];
        if(weaponId)
        {
            this.curSelectId = weaponId;
        }
        this.addParticle();
    }

    public addParticle()
    {
        let curWeaponId = this.curSelectId;
        let data = WeaponTpl.instance().getWeaponDataByWeaponId(curWeaponId);
        this.knife.setUI(data);
        if(data.effect != '')
        {
            let texture = RES.getRes(data.effect);
            let config = RES.getRes("particle_52_json");
            this.system = new particle.GravityParticleSystem(texture, config);
            this.game_group.addChildAt(this.system,0);
            this.system.emitterX = this.knife.x;
            this.system.emitterY = this.knife.y + 20;
        }
        else
        {
            this.system = null;
        }
    }

    public showParticle()
    {
        if(this.system)
        {
            this.system.emitterX = this.knife.x;
            this.system.emitterY = this.knife.y + 20;
            this.system.start();
        }
    }

    public hidePaticle()
    {
        if(this.system)
        {
            this.system.stop();
        }
    }

    public addEvent()
    {
        this.game_group.addEventListener( egret.TouchEvent.TOUCH_BEGIN,this.onTouchBeginHandler,this );
        this.game_group.addEventListener( egret.TouchEvent.TOUCH_MOVE,this.onTouchMoveHandler,this );
        this.game_group.addEventListener( egret.TouchEvent.TOUCH_END,this.onTouchEndHandler,this );
        this.game_group.addEventListener( egret.TouchEvent.TOUCH_RELEASE_OUTSIDE,this.onTouchEndHandler,this );
        GameUtil.addEventListener(EventConst.ENDLESS_CHANGE_WEAPON, this.setWeaponId, this);

        this.btn_home.addTapHandler(this.backHome, this);
    }

    protected backHome()
    {
        let self = this;
        let sureCall = function()
        {
            ScreenMovies.MovieStart(2,()=>{
            let da = {
                index:0
            }
            UIManager.instance().openUILogic(MainUI, da);
            },self);
        }
        let data = {
            tips:'确定回到主页?',
            sureCall:sureCall,
            isPop:true,
            effect:1,
            scope:this
        }
        GameUtil.openConfirmUI(data)
    }

    public addFruit()
    {
        let fruitNum = GameConst.furitNum;
        let fruit_id = Math.floor(Math.random()* fruitNum + 1);
        let fruit: fruit = this.getFruit(fruit_id);
        if(!this.game_group.contains(fruit))
        this.game_group.addChildAt( fruit ,0);
        let flag = Math.random() > 0.5 ? 1 : -1;
        fruit.born2(flag);
        fruit.x = flag == 1 ? -20 : 740;
        fruit.y = Math.random() * 10 + 300;
        this.fruitList.push(fruit);
    }

    public getFruit(id)
    {
        let data = DataJson.fruit_data[id];
        let fruit = FruitPool.getFruit(data);
        return fruit;                                                                                                    
    }

    protected update()
    {
        let list = this.fruitList;
        let cutTime = egret.getTimer();
        if(cutTime - this.mStartTime >= this.mMS)
        {
            this.addFruit();
            this.mStartTime = cutTime;
        }
        this.count++;
        if(this.count >= 120)
        {   
            this.count = 0;
            this.addBomb();
        }
        this.updateFruit();
        this.updateBoom();
        // this.checkHitBomb();
        return false;
    }

    public updateBoom()
    {
        let list = this.bombList;
        for(let v of list)
        {
            v.action_1();
            if(v.y >= 1000)
            {
                let index = list.indexOf(v);
                list.splice(index, 1);
                egret.Tween.get(v).to({
                    alpha : 0
                }, 300).call(()=>{
                    v.reset();
                })
                continue;
            }
        }
    }

    public updateFruit()
    {
        let list = this.fruitList;
        for(let v of list)
        {
            v.action();
            if(v.y >= 700)
            {
                let index = list.indexOf(v);
                list.splice(index, 1);
                this.addBoom(v);
                this.showMiss();
                continue;
            }
        }
    }
    
    public checkHitFruit()
    {
        if(this.count % 2 == 0)
        {
            let list = this.fruitList;
            for(let v of list)
            {
                if(this.knife.visible && this.checkHit(v))
                {
                    let index = list.indexOf(v);
                    list.splice(index, 1);
                    this.curCombNum++;
                    this.curHitTotalNum++;
                    if(this.curCombNum > 3)
                    this.showCombEffect();
                    this.addBoom(v);
                }
            }
        }
        this.addScore();
    }

    public addScore()
    {
        let score = Math.floor(this.curHitTotalNum * GameConst.oneFruitScore + this.curCombNum * GameConst.combAdd);
        this.lb_score.text = score+'';
    }

    public showMiss()
    {
        if(this.curCombNum > this.combHeightNum)
        {
            this.combHeightNum = this.curCombNum;
        }
        this.curCombNum = 0;
        EffectUtil.instance().StopEffect(this.img_miss);
        this.img_miss.alpha = 1;
        this.img_miss.visible = true;
        this.img_miss.scaleX = this.img_miss.scaleY = 0;
        this.img_miss.y = 660;
        egret.Tween.get(this.img_miss).to({
            scaleX:3,
            scaleY:3,
            alpha:0,
            y:this.img_miss.y - 300
        }, 500);
    }

    //展示连击效果
    public showCombEffect()
    {
        this.floatWord_group.visible = true;
        EffectUtil.instance().StopEffect(this.floatWord_group);
        this.floatWord_group.scaleX = this.floatWord_group.scaleY = 0;
        this.lb_count.text = this.curCombNum + '';
        egret.Tween.get(this.floatWord_group).to({
            scaleX:1,
            scaleY:1
        },100,egret.Ease.backOut).wait(100).to({
            scaleX:0,
            scaleY:0
        },100);
    }

    // public cutAllFruit()
    // {
    //     let list = this.fruitList;
    //     for(let i in list)
    //     {
    //         let fruit = list[i] as fruit;
    //         let fruitData = fruit.Data;
    //         let data = {
    //             id:fruitData.id,
    //             color:fruitData.color
    //         }
    //         let item = fruitBoomItem.getBoomItem(data);
    //         if(!this.game_group.contains(item))
    //         this.game_group.addChildAt(item,1);
    //         item.x = fruit.x;
    //         item.y = fruit.y;
    //         item.boom(fruit.boom, fruit);
    //     }
    //     this.gameOver();
    // }

    private gameOver()
    {
        this.removeAllBomb();
        this.game_group.touchEnabled = false;
        let data = {
            isPop:true,
            count:this.curHitTotalNum,
            score:this.lb_score.text
        }
        UIManager.instance().openUILogic(EndLessAccountUI, data);
    }

    public removeAllBomb()
    {
        for(let v of this.bombList)
        {
            v.remove();
        }
        this.bombList = [];
        Boom.clearPool();
    }

    // public checkHitBomb()
    // {
    //     let list = this.bombList;
    //     for(let v of list)
    //     {
    //         v.action_1();
    //         if(v.y >= 700)
    //         {
    //             egret.Tween.get(v).to({
    //                 alpha : 0
    //             }, 300).call(()=>{
    //                 let index = list.indexOf(v);
    //                 list.splice(index, 1);
    //                 v.reset();
    //             })
    //             continue;
    //         }
    //         let x = v.x + v.width / 2
    //         let y = v.y + v.height / 2;
    //         if(this.knife.visible && this.knife.hitTestPoint(x, y, true))
    //         {
    //             SoundManager.instance().stop();
    //             SoundManager.instance().playSound('bomb_mp3',1);
    //             egret.stopTick(this.update, this);
    //             this.knife.visible = false;
    //             this.hidePaticle();
    //             v.boom();
    //             let x = this.img_bg.x;
    //             let y = this.img_bg.y;
    //             egret.Tween.get(this.img_bg).to({
    //                 x:x + 35
    //             },50).to({
    //                 x:x - 35
    //             },50).to({
    //                 x:x + 35
    //             },50).to({
    //                 x:x - 35
    //             },50).to({
    //                 x:x + 35
    //             },50).to({
    //                 x:x - 35
    //             },50).to({
    //                 x:x + 35
    //             },50).to({
    //                 x:x - 35
    //             })
    //         }
    //     }
    // }

    protected addBomb()
    {
        let bomb = Boom.getBomb();
        if(!this.contains(bomb))
        this.addChildAt( bomb ,10);
        let flag = Math.random() > 0.5 ? 1 : -1;
        bomb.x = flag == 1 ? -20 : 740;
        bomb.y = Math.random() * 10 + 400;
        bomb.born_2(flag);
        this.bombList.push(bomb)
    }

    protected checkHit(v)
    {
        let worldPoint = this.game_group.localToGlobal(v.x, v.y, this.worldPoint);
        for(let i=1;i<=9;i++)
        {
            let x = worldPoint.x + Math.floor((i - 1) % 3) * (v.width / 2);
            let y = worldPoint.y + Math.floor(i / 4) * (v.height + 2);
            if(this.knife.hitTestPoint(x, y))
            {
                return true;
            }
        }
    }

    public addBoom(fruit:fruit)
    {
        //添加爆炸效果
        let fruitData = fruit.Data;
        let data = {
            id:fruitData.id,
            color:fruitData.color
        }
        let item = fruitBoomItem.getBoomItem(data);
        if(!this.game_group.contains(item))
        this.game_group.addChildAt(item,1);
        item.x = fruit.x;
        item.y = fruit.y;
        item.boom(fruit.killed, fruit);
        WeChatgGameManager.instance().vibrateShort();
    }

    protected onTouchBeginHandler(e:egret.TouchEvent)
    {
        this.touchId = e.touchPointID;
        this.mIsDown = true;
        let localPoint = this.game_group.globalToLocal(e.stageX, e.stageY,this.worldPoint);
        this.knife.x = localPoint.x;
        this.knife.y = localPoint.y;
        this.touchX = e.stageX;
        this.touchY = e.stageY;
        this.knife.visible = true;
        this.showParticle();
        EffectUtil.instance().rotationEffect(this.knife, 300);
    }

    protected onTouchMoveHandler(e:egret.TouchEvent)
    {
        if(this.touchId != e.touchPointID)
        {
           return;
        }
        if(this.mIsDown && !this.isGameOver){
            let deltX = e.stageX - this.touchX;
            let deltY = e.stageY - this.touchY;
            let _x: number = e.stageX;
            let _y: number = e.stageY;
            this.touchX = e.stageX;
            this.touchY = e.stageY;
            this.knife.x += deltX;
            this.knife.y += deltY;
            this.checkHitBoom(_x,_y);
            this.checkHitFruit();
            if(this.system)
            {
                this.system.emitterX = this.knife.x;
                this.system.emitterY = this.knife.y;
            }
        }
    }

    protected checkHitBoom(_x, _y)
    {
        let list = this.bombList;
        let count = list.length;
        if(count <= 0)return;
        for(let i=0;i<count;i++)
        {
            let boom = list[i];
            if(( _x > (boom.x - boom.width / 2) ) && ( _x < (boom.x + boom.width / 2) )
            && ( _y > (boom.y - boom.height / 2) ) && ( _y < (boom.y + boom.height / 2) ))
            {
                SoundManager.instance().stop();
                SoundManager.instance().playSound('bomb',1);
                egret.stopTick(this.update, this);
                this.knife.visible = false;
                this.hidePaticle();
                boom.boom();
                let x = this.img_bg.x;
                let y = this.img_bg.y;
                egret.Tween.get(this.img_bg).to({
                    x:x + 35
                },50).to({
                    x:x - 35
                },50).to({
                    x:x + 35
                },50).to({
                    x:x - 35
                },50).to({
                    x:x + 35
                },50).to({
                    x:x - 35
                },50).to({
                    x:x + 35
                },50).to({
                    x:x
                })
            } 
        }
        
    }

    public cutAllFruit()
    {
        let list = this.fruitList;
        for(let i in list)
        {
            let fruit = list[i] as fruit;
            let fruitData = fruit.Data;
            let data = {
                id:fruitData.id,
                color:fruitData.color
            }
            this.addBoom(fruit);
        }
        this.gameOver();
    }

    protected onTouchEndHandler(e:egret.TouchEvent)
    {
        if(this.touchId != e.touchPointID)
        return;
        this.mIsDown = false;
        this.knife.visible = false;
        EffectUtil.instance().StopEffect(this.knife);
        this.hidePaticle();
    }

    public gameStart()
    {
        this.touchChildren = true;
        egret.startTick(this.update, this);
    }

    public removeEvent()
    {
        this.game_group.removeEventListener( egret.TouchEvent.TOUCH_BEGIN,this.onTouchBeginHandler,this );
        this.game_group.removeEventListener( egret.TouchEvent.TOUCH_MOVE,this.onTouchMoveHandler,this );
        this.game_group.removeEventListener( egret.TouchEvent.TOUCH_END,this.onTouchEndHandler,this );
        this.game_group.removeEventListener( egret.TouchEvent.TOUCH_RELEASE_OUTSIDE,this.onTouchEndHandler,this );
        GameUtil.removeEventListener(EventConst.ENDLESS_CHANGE_WEAPON, this.setWeaponId, this);
        this.btn_home.removeTapHandler();
        egret.stopTick(this.update, this);
    }

    public clearData()
    {
        this.removeAllBomb();
        for(let v of this.fruitList)
        {
            v.remove();
        }
        this.fruitList = [];
        FruitPool.clearPool();

        this.game_group.removeChildren();
        fruitBoomItem.clearPool();

        this.curHitTotalNum = null;
        this.curCombNum = null;
        this.combHeightNum = null;
    }

    public clear()
    {
        super.clear();
        this.curSelectId = null;
        this.worldPoint = null;
        this.clearData();
    }
}